package com.neulogistics.core.customercenter.api.application.query;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neulogistics.core.customercenter.api.application.converter.CustomerPOVMConverter;
import com.neulogistics.core.customercenter.api.application.converter.CustomerQueryPOConverter;
import com.neulogistics.core.customercenter.api.application.viewmodel.CustomerViewModel;
import com.neulogistics.core.customercenter.infrastructure.persistence.orm.po.CustomerPO;
import com.neulogistics.core.customercenter.infrastructure.persistence.orm.service.ICustomerPOService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CustomerQueryService implements ICustomerQueryService{
    @Resource
    ICustomerPOService customerPOService;


    @Override
    public CustomerViewModel getCustomerById(Integer id) {
        CustomerPO customerPO = customerPOService.getById(id);
        CustomerViewModel customerViewModel = CustomerPOVMConverter.POToVM(customerPO);
        return customerViewModel;
    }

    @Override
    public Page<CustomerViewModel> getCustomerByPage(CustomerQuery customerQuery) {
        // 取出条件
        CustomerPO customerPOQuery = CustomerQueryPOConverter.queryToPO(customerQuery);
        long current = customerQuery.getPageNum();
        long pageSize = customerQuery.getPageSize();

        // 查询
        QueryWrapper<CustomerPO> queryWrapper = new QueryWrapper<>(customerPOQuery);
        Page<CustomerPO> page = customerPOService.page(new Page<>(current, pageSize), queryWrapper);

        // 构造结果
        Page<CustomerViewModel> viewModelPage = new Page<>(current, pageSize);
        List<CustomerViewModel> viewModelList = page.getRecords().stream()
                .map(CustomerPOVMConverter::POToVM).collect(Collectors.toList());
        viewModelPage.setRecords(viewModelList);
        viewModelPage.setTotal(page.getTotal());

        return viewModelPage;
    }


}
